import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { getResourceList } from '@/api/user'
import storage from 'store' // NProgress Configuration
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { i18nRender } from '@/locales'
import { navLog } from '@/api/logApi'
import { calcIndexRoutePath } from '@/utils/utils'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const loginRoutePath = '/user/login'

router.beforeEach(async (to, from, next) => {
  NProgress.start() // start progress bar
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`))
  const userInfo = storage.get('USERINFO')
  if (userInfo) {
    if (to.path === '/') {
      next({ path: await calcIndexRoutePath() })
      NProgress.done()
      return
    }
    if (to.path === loginRoutePath) {
      next({ path: await calcIndexRoutePath() })
      NProgress.done()
    } else {
      logNav(userInfo, to)
      if (store.state.addRouters.length === 0) {
        const params = {
          userId: userInfo.userInfo.userId
        }
        getResourceList(params).then(res => {
          let menuInfo = []
          if (res.retCode === 0) {
            menuInfo = res.retObj
          }
          store.dispatch('GenerateRoutes', { menuInfo }).then(() => {
            router.addRoutes(store.state.addRouters)

            // 请求带有 redirect 重定向时，登录自动重定向到该地址
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            if (to.path === redirect) {
              // set the replace: true so the navigation will not leave a history record
              next({ ...to, replace: true })
            } else {
              // 跳转到目的路由
              next({ path: redirect })
            }
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (to.path === loginRoutePath) {
      next()
    } else {
      next({ path: loginRoutePath })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})

function logNav (userInfo, to) {
  const params = {
    userId: userInfo.userInfo.userId,
    userName: userInfo.userInfo.userName,
    realName: userInfo.userInfo.realName,
    logType: '3',
    module: to.meta.title,
    bz: ''
  }
  navLog(params)
}

